﻿/* 版本记录
 * 0000 20160921 by linson 新增登录窗口，取消其他登录窗体
 * 0002 20170505 by linson 账号输入不用区分大小写，由程序转为大写
 * */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.IO;
using GKQC.DbHelper.DbModels;
using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.Services;
using GKQC.Language;
using Microsoft.VisualBasic.Devices;

namespace GKQC
{
    public partial class LoginForm : Form
    {
        string userCode = string.Empty;
        string departmentCode = string.Empty;
        Dictionary<string, Form> formList = new Dictionary<string, Form>();
        AllDbContext dbContext;
        readonly string LoginUserListFile = "LoginUserList";
        Version curVer = Assembly.GetExecutingAssembly().GetName().Version; //获取当前程序版本

        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginForm()
        {
            InitializeComponent();
            try
            {
                try { 
                    dbContext = new AllDbContext();
                    try { UpdateScriptHelper.UpdateScript(dbContext); } catch (Exception ex) {
                        Logger.LogError(ex);
                    }
                }
                catch(Exception ex)
                {
                    QMessageBox.Show("請先設置數據庫","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }

                Settings.CreateSettingFile();
                this.versionLabel.Text = "版本:" + curVer.ToString();
                QcFormBase.Version = curVer.ToString();

                GetLoginUserList();
                chkModiPass_CheckedChanged(null,null);

                //CheckUpdate();

                LanguageHelper.SetControlLanguageText(this);
            }
            catch (Exception ex)
            {
                Common.Logger.LogError(ex);
                QMessageBox.Show(ex.Message);
            }
        }

        void GetLoginUserList()
        {
            try
            {
                List<string> oldUsers = Settings.GetDataObjectFile<List<string>>(LoginUserListFile);
                if (oldUsers != null && oldUsers.Count > 0)
                {
                    txtUserCode.Items.Clear();
                    txtUserCode.Items.AddRange(oldUsers.ToArray());
                    txtUserCode.SelectedIndex = 0;
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        void SaveLoginUserList(string userCode)
        {
            try
            {
                List<string> oldUsers = new List<string>();
                oldUsers.Add(userCode);
                if (txtUserCode.Items.Count >0)
                {
                    for(int i=0;i< txtUserCode.Items.Count;i++)
                    {
                        string u = txtUserCode.Items[i].ToString();
                        if (!oldUsers.Contains(u))
                            oldUsers.Add(u);
                    }
                }

                Settings.SaveObject(oldUsers, LoginUserListFile);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        void CheckUpdate()
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                string updatePath = string.Empty;
                updatePath = SysParamService.GetSysParamValue(dbContext, "UpdatePath");
                if (string.IsNullOrWhiteSpace(updatePath))
                    updatePath = AppDomain.CurrentDomain.BaseDirectory + "update";

                //updatepath.txt
                string s = Path.Combine(System.Environment.CurrentDirectory, "updatepath.txt");
                string updateExePath_new = Path.Combine(updatePath, "GKQC.Update.exe");
                string updateExePath = Path.Combine(System.Environment.CurrentDirectory, "GKQC.Update.exe");
                if (File.Exists(s))
                {
                    try
                    {
                        File.Delete(s);

                        //GKQC.Update.exe
                        if (File.Exists(updateExePath_new))
                            File.Copy(updateExePath_new, updateExePath,true);

                        Thread.Sleep(500);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                    }
                }

                using (StreamWriter sw = new StreamWriter(s))
                {
                    sw.WriteLine(updatePath);
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }

                sb.AppendLine("Sysparam UpdatePath: " + updatePath);

                //共享文件夹的目录
                //DirectoryInfo serverPath = new DirectoryInfo(updatePath);
                //相对共享文件夹的路径
                string versionFile = @"\updateversion.txt";
                //获取保存文件的路径
                string versionFileName = updatePath + versionFile;
                //执行方法
                string updateVersionString = Tools.ReadTextFileFirstRow(versionFileName);
                if (string.IsNullOrWhiteSpace(updateVersionString) || !updateVersionString.StartsWith("2")) return;
                Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                if (!assembly.GetName().Version.ToString().StartsWith("2")) return;
                Version updateVersion = new Version(updateVersionString);
                if (updateVersion <= assembly.GetName().Version) return;

                if (MessageBox.Show(
                    "有新的程序，是否立即更新？\r\n更新前請先關閉已打開的檢測軟件...", "更新提示"
                    , MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == DialogResult.No)
                    return;

                UpdateScriptHelper.UpdateScript(dbContext);

                if (File.Exists("GKQC.Update.exe") && !isupdating)
                {
                    isupdating = true;
                    this.Close();
                    this.Dispose();
                    Process.Start("GKQC.Update.exe");
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        public static bool isupdating = false;
        private void FLogin_Closed(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //重置
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //登录
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            lblErrorMsg.Text = string.Empty;
            if (string.IsNullOrWhiteSpace(txtUserCode.Text))
            {
                lblErrorMsg.Text = LanguageHelper.GetLanguageText("请输入用户代号");
                txtUserCode.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtPwd.Text))
            {
                lblErrorMsg.Text = LanguageHelper.GetLanguageText("请输入密码");
                txtPwd.Focus();
                return;
            }

            #region 修改密碼驗證
            if (chkModiPass.Checked)
            {
                if(string.IsNullOrWhiteSpace(txtNewPwd.Text))
                {
                    lblErrorMsg.Text = LanguageHelper.GetLanguageText("请输入新密码");
                    txtNewPwd.Focus();
                    return;
                }
            }
            if (chkModiPass.Checked)
            {
                if (string.IsNullOrWhiteSpace(txtConfirmPwd.Text))
                {
                    lblErrorMsg.Text = LanguageHelper.GetLanguageText("请输入確認密码");
                    txtConfirmPwd.Focus();
                    return;
                }
            }
            if (chkModiPass.Checked)
            {
                if (txtNewPwd.Text != txtConfirmPwd.Text)
                {
                    lblErrorMsg.Text = LanguageHelper.GetLanguageText("兩次輸入的新密碼不一致");
                    txtConfirmPwd.Focus();
                    return;
                }
            }
            #endregion 修改密碼驗證

            try
            {
                UserModel user = dbContext.QcDb.Queryable<UserModel>().Where(u => u.UserCode == txtUserCode.Text).Single();
                if (user == null)
                {
                    lblErrorMsg.Text = LanguageHelper.GetLanguageText("用户不存在！");
                    txtUserCode.Focus();
                    return;
                }

                if(!user.IsUse)
                {
                    lblErrorMsg.Text = LanguageHelper.GetLanguageText("該用户已被禁用！");
                    txtUserCode.Focus();
                    return;
                }

                var en = EncryptSugar.GetInstance();
                if (txtPwd.Text != en.Decrypto(user.Password.Substring(0, user.Password.Length - 50)))
                {
                    lblErrorMsg.Text = LanguageHelper.GetLanguageText("密码错误！");
                    txtPwd.Focus();
                    return;
                }

                user.LoginTime = DateTime.Now;
                user.LoginServerTime = user.LoginTime;
                user.OnlineId = System.Guid.NewGuid().ToString();
                DateTime? serverTime = dbContext.GetServerTime();
                if (serverTime.HasValue)
                    user.LoginServerTime = serverTime.Value;

                //獲取權限
                user.UserRights = dbContext.QcDb.Queryable<UserRightModel>()
                    .Where(r => r.UserCode == user.UserCode && r.Type=="user")
                    .ToList();
                if (user.UserRights == null) user.UserRights = new List<UserRightModel>();

                user.UserGroupRights = dbContext.QcDb.Queryable<UserRightModel>()
                    .Where(r => r.UserCode == user.GroupCode && r.Type == "usergroup")
                    .ToList();
                if (user.UserGroupRights == null) user.UserGroupRights = new List<UserRightModel>();

                SysLogService.Log(dbContext, user, this, LanguageHelper.GetLanguageText("登錄"), string.Empty,string.Empty);
                SysLogService.Log(dbContext, user, this, "登录", FormCommon.GetCpuId(),
    versionLabel.Text + "，IP地址：" + FormCommon.GetLocalIP() + "，操作系统： " + new ComputerInfo().OSFullName
     );

                #region 修改密碼
                if (chkModiPass.Checked)
                {
                    EncryptSugar encryptSugar = EncryptSugar.GetInstance();
                    string newPassword = encryptSugar.Encrypto(txtNewPwd.Text) + RandomSugar.GetRandWord(50);
                    user.Password = newPassword;
                    dbContext.QcDb.Updateable<UserModel>(user).UpdateColumns(u => new { u.Password }).ExecuteCommand();
                }
                #endregion 修改密碼

                //试用版
                if( 
                    (double.Parse(user.GetServerTime().ToString("yyyyMM")) >= 202108) && 1==2
                    )
                {
                    DateTime serverTime2 = user.GetServerTime();
                    if (1 == 1 && double.Parse(serverTime2.ToString("ss")) % 2 == 0
                        || double.Parse(serverTime2.ToString("ss")) % 3 == 0
                        || double.Parse(serverTime2.ToString("ss")) % 5 == 0
                    )
                    {
                        QMessageBox.Show("发生未知错误，请联系管理员", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                SaveLoginUserList(user.UserCode);

                MainForm11 f = new MainForm11(user);
                f.Show();
                this.Hide();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"异常S0005",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }


        //修改密码
        private void checkBox1_Click(object sender, EventArgs e)
        {
            if (chkModiPass.Checked)
            {
                lblNewPwd.Visible = true;
                lblConfirmPwd.Visible = true;
                txtNewPwd.Visible = true;
                txtConfirmPwd.Visible = true;
            }
            else
            {
                lblNewPwd.Visible = false;
                lblConfirmPwd.Visible = false;
                txtNewPwd.Visible = false;
                txtConfirmPwd.Visible = false;
            }
        } 

        //关闭GKQC相关程序 20170328 by linson
        private void KillGKQC()
        {
            try
            {
                Process[] p = System.Diagnostics.Process.GetProcesses();
                for (int i = 0; i < p.Length; i++)
                {
                    if (p[i].ProcessName.ToLower().Contains("GKQC"))
                    {
                        p[i].Kill();
                    }
                }
            }
            catch(Exception ex)
            {
                
            }
        }

        //程序下载
        private void label6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://192.168.0.17:8089/PC.rar");
        }

        private void chkModiPass_CheckedChanged(object sender, EventArgs e)
        {

            lblNewPwd.Visible = chkModiPass.Checked;
            lblConfirmPwd.Visible = chkModiPass.Checked;
            txtNewPwd.Visible = chkModiPass.Checked;
            txtConfirmPwd.Visible = chkModiPass.Checked;

            if (chkModiPass.Checked)
            {
                this.Height = 422;
                btnOK.Location = new Point(btnOK.Location.X, 284);
                btnCancel.Location = new Point(btnCancel.Location.X, 284);
                this.versionLabel.Location = new Point(versionLabel.Location.X, 331);
            }
            else
            {
                this.Height = 322;
                btnOK.Location = new Point(btnOK.Location.X, 184);
                btnCancel.Location = new Point(btnCancel.Location.X, 184);
                this.versionLabel.Location = new Point(versionLabel.Location.X, 231);
            }
        }

        private void lblDataBase_Click(object sender, EventArgs e)
        {
            FormStringSetting f = new FormStringSetting();
            f.ShowDialog();
            try
            {
                dbContext = new AllDbContext();
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtUserCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtPwd.Focus();
                lblErrorMsg.Text = string.Empty;
            }
        }

        private void txtPwd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                btnOK.PerformClick();
        }

        private void LoginForm_Shown(object sender, EventArgs e)
        {
            CheckUpdate();
        }

        private void lblhelp_Click(object sender, EventArgs e)
        {
            if (Environment.Is64BitOperatingSystem && File.Exists("Help_64.exe"))
                Process.Start("Help_64.exe");
            else if (!Environment.Is64BitOperatingSystem && File.Exists("Help_32.exe"))
                Process.Start("Help_32.exe");
            else if (File.Exists("Help.exe"))
                Process.Start("Help.exe");
        }
    }
}